<?php

namespace App\Jobs;

use App\Models\Admin;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;

class SendEmailCreateList implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * 第一个队列任务（生产者） SendEmailCreateList Job
     * @return void
     */
    public function handle()
    {
    	//断点续传的id
		$continue_id = Redis::get('send_mail_continue_id');
//		foreach (User::query()->select('email')->cursor() as $flight) {
//
//			$users[] = json_encode($flight->toArray(),JSON_UNESCAPED_UNICODE);
//
//			//每取500条 将用户邮箱入列
//			if(count($users) == 500){
//
//				Redis::lpush('send_email_arr',$users);
//				$users = [];
//
//				//通知消费队列
//				if($start_flag == 0){
//					$this->dispatch(new SendNotifyEmail('send_email_arr'));
//					$start_flag = 1; //防止重复通知
//				}
//			}
//		}
		//如果没有，就直接操作任务
		if(!$continue_id){
			foreach (User::query()->select('username','id')->cursor() as $user_item) {

				//用于断点续传的id 保存有效期为1天
				Redis::setex('send_mail_continue_id',86400,$user_item->id);

				$user = json_encode($user_item->toArray());

				Redis::lpush('send_email_arr',serialize($user));
			}
		}else{
			//如果有，就续传任务
			foreach (User::query()->where('id','>',$continue_id)->select('username','id')->cursor() as $user_item) {

				//用于断点续传的id 保存有效期为1天
				Redis::setex('send_mail_continue_id',86400,$user_item->id);

				$user = json_encode($user_item->toArray());

				Redis::lpush('send_email_arr',serialize($user));
			}
		}


    }
}
